package cn.com.bluemoon.daps.model.core.file.parser;

import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.model.core.file.TableInfoDto;
import cn.com.bluemoon.daps.model.core.file.config.GlobalParserConfig;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;

/**
 * sql解析器
 *
 * @author Jarod.Kong
 * @date 2021/3/11 13:58
 */
public class SqlFileParser extends AbstractFileParser {
    public SqlFileParser() {
    }

    public SqlFileParser(GlobalParserConfig globalParserConfig) {
        super(globalParserConfig);
    }

    @Override
    public ResultBean<List<TableInfoDto>> parser(File file) {
        try {
            List<String> allLines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
            if (!allLines.isEmpty()) {
                String sqls = StrUtil.trim(String.join("", allLines));
                List<SQLStatement> sqlStatement = SQLUtils.parseStatements(sqls, getGlobalParserConfig().getDbType());
                for (SQLStatement statement : sqlStatement) {
                    System.out.println(statement);
                    // FIXME: 2021/3/12 参考测试类{@link com.bluemoon.model.test.dbimport2.BmReadSqlTest}
                }
                System.out.println();
                return ResultBean.ok(Collections.emptyList());
            }
            return ResultBean.error("文件内容为空");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultBean.error("sql解析功能，TBD");
    }

}
